import { GameManager } from "../Logic/GameManager";
import { VisualEntityManager } from "../Visual/VisualEntityManager";
import { MsgDispatcher } from "../Framework/Network/MsgDispatcher";
import { InputMessageEnum } from "../Framework/Network/InputMessageEnum";
import { SanguoxiaoGame } from "../Logic/Game/SanguoxiaoGame";
import { loadResource, waitInterval } from "../Framework/ResourceManager/ResLoader";
import { loadScene } from "../Framework/ResourceManager/SceneLoader";


export class ProcGame {

    gameManager: GameManager;
    visual: VisualEntityManager;
    operation: any = null;

    async onEnter() {

        await loadScene("Game", null);

        MsgDispatcher.getInstance().registerMsg(InputMessageEnum.ShortPress, this.onShortPress);
        MsgDispatcher.getInstance().registerMsg(InputMessageEnum.LongPress, this.onLongPress);
        MsgDispatcher.getInstance().registerMsg(InputMessageEnum.Up, this.onUp);

        this.visual = new VisualEntityManager();
        let tileBirdPromise = await loadResource("prefab/tileBird", null);
        let tileFishPromise = await loadResource("prefab/tileFish", null);
        let tileHorsePromise = await loadResource("prefab/tileHorse", null);
        let tileSwordPromise = await loadResource("prefab/tileSword", null);
        let tileBombPromise = await loadResource("prefab/tileBomb", null);
        let tileSpacePromise = await loadResource("prefab/tileSpace", null);
        this.visual.tiles = [tileBirdPromise, tileFishPromise, tileHorsePromise, tileSwordPromise, tileBombPromise, tileSpacePromise];
        let gameLogic = new SanguoxiaoGame();
        this.gameManager = new GameManager(gameLogic);

        gameLogic.init(this.gameManager);
        return true;
    }

    onProcess(dt) {
        let operation = this.operation;
        this.operation = null;
        this.gameManager.tick(dt, operation);
        this.visual.tick(dt);
    }

    onLeave() {
        MsgDispatcher.getInstance().unregisterMsg(InputMessageEnum.ShortPress, this.onShortPress);
        MsgDispatcher.getInstance().unregisterMsg(InputMessageEnum.LongPress, this.onLongPress);
        MsgDispatcher.getInstance().unregisterMsg(InputMessageEnum.Up, this.onUp);

        this.gameManager.destroy();
        this.visual.destroy();
        this.gameManager = null;
        this.visual = null;
    }

    onShortPress = (param: any[]) => 
    {
        this.operation = {"operation": InputMessageEnum.ShortPress, "coord": param[0]}; 
    }

    onLongPress = (param: any[]) => {
        this.operation = {"operation": InputMessageEnum.LongPress, "coord": param[0]};
    }

    onUp = (param: any[]) => {
        this.operation = {"operation": InputMessageEnum.Up};
    }
}
